<template>
    <div class="app-container">
        <CommonSidebar />

        <div class="main-content">
            <div class="image-conversion">
                <!-- Left Section: Upload and Preview -->
                <div class="left-section">
                    <!-- Preview Section -->
                    <div class="preview-section" v-if="!showInpaintTools && imageUrl">
                        <vue-cropper ref="cropperRef" :img="imageUrl" :info="true" :output-size="1" :can-move="true"
                            :auto-crop="cropperOptions.aspectable" :centerBox="true" dragMode="crop" outputType="png" />
                    </div>
                    <CanvasDrawing v-if="showInpaintTools" :imageUrl="imageUrl" :brushWidth="isEraser ? eraserSize : brushSize"
                    :isDrawingMode="true" :isEraserMode="isEraser" ref="canvasRef" :canvasHeight="750" :canvasWidth="1200"/>

                </div>

                <!-- Right Section: Tools -->

                <div class="right-section">
                    <h3>编辑工具</h3>
                    <div class="tool-section">
                        <label class="tool-group">
                            <el-upload class="tool-button" action="/api/upload" :show-file-list="false" accept="image/*"
                                :before-upload="beforeUpload" :on-success="handleUploadSuccess" id="upload-button">
                                替换图片
                            </el-upload>
                        </label>
                        <h4>工具</h4>
                        <div class="tool-group" v-if="!showInpaintTools">
                            <div class="tool-item">
                                <div class="tool-item-icon">
                                    <Plus />
                                </div>
                                裁剪(待开发)
                            </div>
                            <div class="tool-item">
                                <div class="tool-item-icon">
                                    <Plus />
                                </div>
                                AI抠图(待开发)
                            </div>
                            <div class="tool-item">
                                <div class="tool-item-icon">
                                    <Plus />
                                </div>
                                滤镜(待开发)
                            </div>
                            <div class="tool-item">
                                <div class="tool-item-icon">
                                    <Plus />
                                </div>
                                AI滤镜(待开发)
                            </div>
                            <div class="tool-item" @click="handleInpaintTool">
                                <div class="tool-item-icon">
                                    <Plus />
                                </div>
                                AI局部重绘
                            </div>
                            <div class="tool-item" @click="handleEnhanceImage">
                                <div class="tool-item-icon">
                                    <Plus />
                                </div>
                                AI变清晰
                            </div>

                            <div class="tool-item">
                                <div class="tool-item-icon">
                                    <Plus />
                                </div>
                                AI扩图(待开发)
                            </div>
                            <div class="tool-item">
                                <div class="tool-item-icon">
                                    <Plus />
                                </div>
                                文字(待开发)
                            </div>
                            <div class="tool-item">
                                <div class="tool-item-icon">
                                    <Plus />
                                </div>
                                标记(待开发)
                            </div>
                            <div class="tool-item">
                                <div class="tool-item-icon">
                                    <Plus />
                                </div>
                                马赛克(待开发)
                            </div>
                        </div>
                        <div class="inpaint-toolbar" v-if="showInpaintTools">
                            <div class="tool-controls">
                                <div class="brush-controls">
                                    <el-button-group>
                                        <el-button :type="!isEraser ? 'primary' : ''" @click="isEraser = false">
                                            <el-icon>
                                                <Brush />
                                            </el-icon>画笔
                                        </el-button>
                                        <el-button :type="isEraser ? 'primary' : ''" @click="isEraser = true">
                                            <el-icon>
                                                <Delete />
                                            </el-icon>橡皮擦
                                        </el-button>
                                    </el-button-group>

                                    <div>
                                        <span>笔刷大小: {{ isEraser ? eraserSize : brushSize }}</span>
                                        <el-slider :model-value="isEraser ? eraserSize : brushSize"
                                            @update:model-value="val => isEraser ? eraserSize = val : brushSize = val"
                                            :min="5" :max="50" />
                                    </div>
                                </div>

                                <div class="prompt-input">
                                    <el-input v-model="inpaintPrompt" type="textarea" :rows="3"
                                        placeholder="描述您想要重绘的内容..." />
                                </div>

                                <el-button type="primary" @click="handleInpaint" block>
                                    生成重绘
                                </el-button>
                            </div>
                        </div>
                        <div class="save-section">
                            <el-button style="background-color: #409EFF; color: white;" @click="handleSave" size="large"
                                block>
                                <el-icon>
                                    <Download />
                                </el-icon>保存图片
                            </el-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- Add dialog component -->
        <el-dialog v-model="dialogVisible" title="AI增强效果" width="50%" :before-close="handleClose">
            <div class="enhanced-image-container">
                <img :src="enhancedImageUrl" v-if="enhancedImageUrl" style="width: 100%" />
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleDownloadEnhanced" type="primary">
                        <el-icon>
                            <Download />
                        </el-icon>下载图片
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import CommonSidebar from '@/components/CommonSidebar.vue'
import { Plus, Crop, Refresh, Picture, Download, Sunny, Monitor } from '@element-plus/icons-vue'
import { VueCropper } from 'vue-cropper'
import 'vue-cropper/dist/index.css'
import { ElMessage } from 'element-plus'
import { Select, Brush, Delete } from '@element-plus/icons-vue'
import { useImagesStore } from '@/store/modules/images';
import CanvasDrawing from "@/components/CanvasDrawing.vue";
const ImagesStore = useImagesStore()
const imageUrl = ref("");
const cropperRef = ref(null)
const showInpaintTools = ref(false);
const inpaintPrompt = ref("")
const isEraser = ref(false);
const brushSize = ref(20);
const eraserSize = ref(20);
const cropperOptions = ref({
    aspectable: false,
})

// Add these refs
const dialogVisible = ref(false)
const enhancedImageUrl = ref('')
const canvasRef = ref(null);

// const getMaskData = () => {
//     if (!fabricCanvas.value) return null
//     return fabricCanvas.value.toDataURL({
//         format: 'png',
//         quality: 1
//     })
// }

const handleInpaintTool = () => {
    if (!imageUrl.value) {
        ElMessage.warning('请先上传图片')
        return
    }
    showInpaintTools.value = true
}
const handleInpaint = async () => {
    if (!inpaintPrompt.value) {
        ElMessage.warning('请输入重绘描述')
        return
    }

    try {
        const maskFile = await canvasRef.value.getCanvasData();
        console.log(maskFile)
        const formData = new FormData();
        formData.append('file', maskFile);
        await ImagesStore.inpaintImage(formData)
        const filename = ImagesStore.uploadmask
        await ImagesStore.fetchEncodedImages({style:'局部重绘',img:filename});
        const data = ImagesStore.encodedImages
        // console.log(data.image)
        dialogVisible.value = true
        enhancedImageUrl.value = data.image
    } catch (error) {
        console.log(error);
        ElMessage.error('重绘失败')
    }
}

// Add these methods
const handleEnhanceImage = async () => {
    if (!imageUrl.value) {
        ElMessage.warning('请先上传图片')
        return
    }
    const imgFileName = imageUrl.value
        ? imageUrl.value.split('/').pop()
        : '';
    console.log(imgFileName)
    const form = {
        style: '图生图',
        img: imgFileName
    }
    try {
        await ImagesStore.fetchEncodedImages(form)
        const { image } = ImagesStore.encodedImages
        dialogVisible.value = true;
        enhancedImageUrl.value = image
        dialogVisible.value = true
    } catch (error) {
        ElMessage.error('图片增强失败')
    }
}

const handleClose = () => {
    dialogVisible.value = false
    enhancedImageUrl.value = ''
}

const handleDownloadEnhanced = () => {
    const link = document.createElement('a')
    link.href = enhancedImageUrl.value
    link.download = 'enhanced-image.png'
    link.click()
    ElMessage.success('下载成功')
}

// 上传前验证
const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/')
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }
    return true
}

// 上传成功处理
const handleUploadSuccess = (res, file) => {
    const originalName = file.name


    imageUrl.value = `http://192.168.1.13:8124/static/input/${originalName}`

    console.log(imageUrl.value)

    ElMessage.success('参考图上传成功')
}

// 保存图片
const handleSave = () => {
    cropperRef.value?.getCropBlob((blob) => {
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = 'edited-image.png'
        link.click()
        ElMessage.success('保存成功')
    })
}

</script>

<style scoped>

.inpaint-toolbar {
    padding: 20px;

}

.tool-controls {
    display: flex;
    flex-direction: column;
    align-items: top;
    gap: 20px;
}

.brush-controls {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.prompt-input {
    margin-top: 10px;
}

.enhanced-image-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 200px;
}

.dialog-footer {
    display: flex;
    justify-content: center;
    width: 100%;
}

.app-container {
    display: flex;
    min-height: 100vh;
}

.main-content {
    flex: 1;
    padding: 40px 20px 20px 20px;
    background-color: #f5f7fa;
}

.image-conversion {
    display: flex;
    background: white;
    border-radius: 8px;
    padding: 0px 0 0 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    height: calc(100vh - 80px);
}

/* Left Section Styles */
.left-section {
    flex: 4;
    display: flex;
    flex-direction: column;
    border-right: 1px solid #ebeef5;
    padding-right: 20px;
    padding-bottom: 20px;
}

.preview-section {
    flex: 1;
    margin-top: 20px;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
}

/* Right Section Styles */
.right-section {
    flex: 1;
    min-width: 310px;
    /* padding: 10px; */
    display: flex;
    flex-direction: column;
}


h3 {
    border-bottom: 1px solid #ebeef5;
    padding: 0 0 20px 20px;
    margin-bottom: 0px;
}

.tool-section {
    padding: 0px 10px 0px 10px;
}

.tool-group {
    border-bottom: 1px solid #ebeef5;
    /* padding: 20px; */
    padding: 20px 0 20px 0;
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    color: black;
}

h4 {
    margin-bottom: 0px;
    padding-bottom: 0px;
    padding-left: 20px;
}

.tool-item {
    margin: 5px;
    font-size: 12px;
    text-align: center;
    max-width: 60px;
}

.tool-item-icon {
    background-color: #ebeef5;
    width: 60px;
    height: 60px;
    padding: 20px;
    box-sizing: border-box;
    border-radius: 10px;
    margin-bottom: 5px;
}

.tool-button {
    background-color: #ebeef5;
    text-align: center;
    padding: 10px;
    font-size: 15px;
    width: 80%;
    border-radius: 10px;
    border: 0px;
}

:deep(.el-upload) {
    color: black
}

.background-preview {
    background-color: #f8f9fa;
}

.save-section {
    margin-top: 20px;
    margin-bottom: 20px;
    padding-left: 20px;
}

:deep(.el-icon) {
    margin-right: 5px;
}

.upload-text {
    margin-top: 10px;
    color: #606266;
}
</style>